package com.syslight.annotationdemo;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.squareup.otto.Subscribe;
import com.syslight.annotationdemo.bus.OttoBus;
import com.syslight.annotationdemo.greeting.GreetingService;
import com.syslight.annotationdemo.orm.DatabaseHelper;
import com.syslight.annotationdemo.orm.User;

import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.BeforeTextChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.TextChange;
import org.androidannotations.annotations.Transactional;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.sql.SQLException;
import java.util.List;

import roboguice.RoboGuice;


@EActivity(R.layout.activity_main)
public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {

    @ViewById
    EditText editTitle;
    @ViewById
    Button buttonClickMe;
    @ViewById
    Button buttonOrmlite;
    @ViewById
    Button buttonOrmliteDelete;
    @ViewById
    Button buttonOrmliteClear;
    @ViewById
    EditText textOperations;
    @ViewById
    Button buttonStartOne;

    @Bean
    OttoBus bus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        background();
        bus.register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bus.unregister(this);
    }

    @Subscribe
    public void onUpdate(Message message) {
        Log.e("Activity", "receive message in MainActivity!");
    }

    @UiThread(delay=0)
    protected void init() {
        Log.d("Activity", "member textTitle: " + textOperations.toString());
        textOperations.setText("大家好，我已经初始化好了!");
    }

    @Background
    protected void background() {
        Log.d("Activity", "hello，各位，我不会在主线程运行哦!" + Thread.currentThread().getId());
        init();
    }

    @BeforeTextChange(R.id.edit_title)
    public void beforeTextChanged() {
//        Toast.makeText(this, "BeforeTextChanged", Toast.LENGTH_SHORT).show();
        Log.e("Activity", "BeforeTextChanged");
    }

    @TextChange(R.id.edit_title)
    public void onTextChanged(TextView tv, CharSequence text) {
//        Toast.makeText(this, "TextChanged!", Toast.LENGTH_SHORT).show();
        Log.e("Activity", "OnTextChanged");
    }

    @AfterTextChange(R.id.edit_title)
    public void afterTextChanged() {
//        Toast.makeText(this, "AfterTextChanged", Toast.LENGTH_SHORT).show();
        Log.e("Activity", "AfterTextChanged");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    boolean inited = false;
    @Click({R.id.button_click_me, R.id.button_ormlite, R.id.button_ormlite_delete,
        R.id.button_ormlite_clear, R.id.button_ormlite_select, R.id.button_start_one})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_click_me:
                if (!inited ) {
                    inited = true;
                    RoboGuice.setBaseApplicationInjector(getApplication(), RoboGuice.DEFAULT_STAGE);
                    RoboGuice.setModulesResourceId(R.array.roboguice_modules);
                }

                GreetingService greetingService = RoboGuice.getInjector(getApplicationContext()).getInstance(GreetingService.class);
                greetingService.sayHello();
                break;
            case R.id.button_ormlite_select:
                select(getHelper().getReadableDatabase());
                break;
            case R.id.button_ormlite:
                insert(getHelper().getWritableDatabase());
                break;
            case R.id.button_ormlite_delete:
                deleteOne(getHelper().getWritableDatabase());
                break;
            case R.id.button_ormlite_clear:
                deleteAll(getHelper().getWritableDatabase());
                break;
            case R.id.button_start_one:
                OneActivity_.intent(this).start();
                break;
            default:
                break;
        }
    }

    @Transactional
    void select(SQLiteDatabase db) {
        try {
            Dao<User, Integer> userDao = getHelper().getUserDAO();
            List<User> users = userDao.queryForAll();
            for (User user : users) {
                textOperations.setText(textOperations.getText() + "\n" + user.toString());
            }
            textOperations.setText(textOperations.getText() + "\n" + "查询数据完毕!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    void insert(SQLiteDatabase db) {
        try {
            Dao<User, Integer> userDao = getHelper().getUserDAO();
            for (int i = 0; i < 9; ++i) {
                User user = new User(i+"", "name_" + i, (i%2 == 0 ) ? "male" : "female");
                userDao.create(user);
            }
            textOperations.setText(textOperations.getText() + "\n" + "增加数据成功!");

            List<User> users = userDao.queryForAll();
            for (User user : users) {
                textOperations.setText(textOperations.getText() + "\n" + user.toString());
            }
            textOperations.setText(textOperations.getText() + "\n" + "插入数据完毕!");
        } catch (SQLException e) {

        }
    }

    @Transactional
    void deleteOne(SQLiteDatabase db) {
        try {
            Dao<User, Integer> userDao = getHelper().getUserDAO();
            QueryBuilder<User, Integer> queryBuilder = userDao.queryBuilder();
            User user = queryBuilder.queryForFirst();
            if (user != null) {
                userDao.delete(user);
                textOperations.setText(textOperations.getText() + "\n delete one:" + user.toString());
            }
            textOperations.setText(textOperations.getText() + "\n" + "删除第一条数据完毕!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    void deleteAll(SQLiteDatabase db) {
        try {
            Dao<User, Integer> userDao = getHelper().getUserDAO();
            List<User> users = userDao.queryForAll();
            for (User user : users) {
                userDao.delete(user);
                textOperations.setText(textOperations.getText() + "\n delete:" + user.toString());
            }
            textOperations.setText(textOperations.getText() + "\n" + "删除所有数据完毕!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
